import OpenAI from "openai";
import type { ChatCompletionMessageParam } from "openai/resources/index.mjs";
import { match } from "ts-pattern";
import fs from 'fs';
import path from 'path';
import { NextResponse } from 'next/server';
// Create an OpenAI API client (that's edge friendly!)

// IMPORTANT! Set the runtime to edge: https://vercel.com/docs/functions/edge-functions/edge-runtime
// export const runtime = "edge";

export async function POST(req: Request): Promise<Response> {

  const configPath = path.join(process.cwd(), 'config.json');
  const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
  
  const openai = new OpenAI({
    baseURL: config.openai.baseURL || 'https://api.deepseek.com',
    apiKey: config.openai.apiKey,
  });
  
  // Check if the API key is set, if not return 400
  if (!config.openai.apiKey || config.openai.apiKey === "") {
    return new Response("Missing OpenAI API key - make sure to add it to config.json file.", {
      status: 400,
    });
  }

  const { prompt, option, command } = await req.json();


  const BASE_ROLE = "你是资深文档工程师，拥有10年以上各类技术文档编写经验.";
  const COMMON_REQUIREMENTS = 
    "◆ 遵循行业最佳实践\n" +
    "◆ 保持文档结构清晰\n" +
    "◆ 确保内容准确完整\n" +
    "◆ 适应不同读者群体\n";
  
  const messages = match(option)
    .with("generate", () => [
      {
        role: "system",
        content:BASE_ROLE+
        "根据现有内容编写专业文档\n" +
        "▼ 核心要求\n" +
        "● 自动识别文档类型\n" +
        "● 采用合适的文档结构\n" +
        "● 保持专业性和可读性\n" +
        COMMON_REQUIREMENTS
      },
      {
        role: "user",
        content: prompt,
      },
    ])
    .with("improve", () => [
      {
        role: "system",
        content:
        BASE_ROLE+
        "根据输入的文档进行优化，要求：\n" +
        "● 提升文档质量\n" +
        "● 优化内容结构\n" +
        "● 保持风格一致\n" +
        COMMON_REQUIREMENTS
      },
      {
        role: "user",
        content: `现有文档是：${prompt}`,
      },
    ])
    .with("shorter", () => [
      {
        role: "system",
        content:
        BASE_ROLE+
       "根据输入的文档进行摘要，要求：\n" +
       "● 保留核心信息\n" +
       "● 适应快速阅读\n" +
       "● 保持原意准确\n" +
       COMMON_REQUIREMENTS
      },
      {
        role: "user",
        content: `现有文档是：${prompt}`,
      },
    ])
    .with("longer", () => [
      {
        role: "system",
        content:
        BASE_ROLE+
        "根据输入的文档进行扩展，要求：\n" +
        "● 补充必要细节\n" +
        "● 保持内容连贯\n" +
        "● 增强文档深度\n" +
        COMMON_REQUIREMENTS
      },
      {
        role: "user",
        content: `现有文档是：${prompt}`,
      },
    ])
    .with("fix", () => [
      {
        role: "system",
        content:
        BASE_ROLE + 
        "检查并修正文档，要求：\n" +
        "● 修正格式和语法\n" +
        "● 优化表达方式\n" +
        "● 提升文档专业性\n" +
        COMMON_REQUIREMENTS
      },
      {
        role: "user",
        content: `现有文档是：${prompt}`,
      },
    ])
    .with("zap", () => [
      {
        role: "system",
        content:
        BASE_ROLE +
          "根据输入的文档和特定要求进行修改\n" +
          "● 保持文档完整性\n" +
          "● 确保修改符合要求\n" +
          COMMON_REQUIREMENTS
      },
      {
        role: "user",
        content: `对于这份文档：${prompt}。请按照以下要求修改：${command}`,
      },
    ])
    .run() as ChatCompletionMessageParam[];
  


  const response = await openai.chat.completions.create({
    model: "deepseek-chat",
    stream: true,
    temperature: 1.2,
    messages,
  });

// Create a ReadableStream from the OpenAI response
const stream = new ReadableStream({
  async start(controller) {
    const encoder = new TextEncoder();
    
    for await (const chunk of response) {
      const content = chunk.choices[0]?.delta?.content || "";
      controller.enqueue(encoder.encode(content));
    }
    controller.close();
  },
});

// Return the stream with proper headers
return new Response(stream, {
  headers: {
    'Content-Type': 'text/plain; charset=utf-8',
    'Transfer-Encoding': 'chunked',
  },
});
}
